<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<%@ include file="../bui_header.jsp" %>

<body>

<div class="container">
    <div class="row">
      <form id="searchForm" class="form-horizontal span24">
        <div class="row">
          <div class="control-group span8">
            <label class="control-label">编号：</label>
            <div class="controls">
              <input type="text" class="control-text" name="number">
            </div>
          </div>
          <div class="control-group span8">
            <label class="control-label">姓名：</label>
            <div class="controls">
              <input type="text" class="control-text" name="name">
            </div>
          </div>
          <div class="control-group span8">
            <label class="control-label">性别：</label>
            <div class="controls" >
              <select name="sex">
              	<option value="">请选择</option>
                <option value="1">男</option>
                <option value="0">女</option>
              </select>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="control-group span8">
            <label class="control-label">部门：</label>
            <div class="controls">
              <input type="text" class="text" name="department">
            </div>
          </div>
          <div class="control-group span8">
            <label class="control-label">职位：</label>
            <div class="controls">
              <input type="text" class="text" name="position">
            </div>
          </div>
          <div class="span4 offset4">
            <button type="button" id="btnSearch" class="button button-primary">搜索</button>
          </div>
        </div>
      </form>
    </div>
    <div class="search-grid-container">
      <div id="grid"></div>
    </div>

  </div>
  <div id="content" class="hide">
      <form id="user_form" class="form-horizontal" action="../data/edit.php?a=1">
        <!-- <input type="hidden" name="a" value="3"> -->
        <div class="row">
          <div class="control-group span8">
            <label class="control-label"><s>*</s>员工编号</label>
            <div class="controls">
              <input name="number" type="text" data-rules="{required:true}" class="input-normal control-text">
            </div>
          </div>
          <div class="control-group span8">
            <label class="control-label"><s>*</s>密码</label>
            <div class="controls">
              <input name="password" type="text" data-rules="{required:true}" class="input-normal control-text">
            </div>
          </div>
        </div>
        <div class="row">
          <div class="control-group span8">
            <label class="control-label"><s>*</s>姓名</label>
            <div class="controls">
              <input name="name" type="text" data-rules="{required:true}" class="input-normal control-text">
            </div>
          </div>
          <div class="control-group span8">
            <label class="control-label"><s>*</s>性别</label>
            <div class="controls">
              <select data-rules="{required:true}"  name="sex" class="input-normal"> 
                <option value="">请选择</option>
                <option value="1">男</option>
                <option value="0">女</option>
              </select>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="control-group span8">
            <label class="control-label"><s>*</s>部门</label>
            <div class="controls">
              <input name="department" type="text" data-rules="{required:true}" class="input-normal control-text">
            </div>
          </div>
          <div class="control-group span8">
            <label class="control-label"><s>*</s>职位</label>
            <div class="controls">
              <input name="position" type="text" data-rules="{required:true}" class="input-normal control-text">
            </div>
          </div>
        </div>
        <div class="row">
          <div class="control-group span8">
            <label class="control-label"><s>*</s>联系方式</label>
            <div class="controls">
              <input name="email" type="text" data-rules="{required:true}" class="input-normal control-text">
            </div>
          </div>
        </div>
      </form>
    </div>
    
    <div id='authSetting'  class="hide"></div>
<!--   <script type="text/javascript">
    BUI.use('common/page');
  </script> -->
  
<script type="text/javascript">

var isAdmin = ${isAdmin};
var authSetting;

BUI.use(['common/search', 'common/page', 'bui/overlay', 'bui/tree', 'bui/data'], 
		function (Search, Overlay, Tree, Data) {
    
    var enumObj = {"1":"男","0":"女"};
    var editing = new BUI.Grid.Plugins.DialogEditing({
        contentId : 'content', //设置隐藏的Dialog内容
        autoSave : false//添加数据或者修改数据时，自动保存
        //triggerCls : 'btn-edit'
      });
    
    var columns = [
        {title:'编号',dataIndex:'number',width:"20%"/* ,
      	  renderer:function(v){
           return Search.createLink({
             id : 'detail' + v,
             title : '学生信息',
             text : v,
             href : 'detail/example.html'
           });
        	  } */
        },
        {title:'姓名',dataIndex:'name',width:'15%'},
        {title:'性别',dataIndex:'sex',width:'5%',
      	  renderer: BUI.Grid.Format.enumRenderer(enumObj)},
        {title:'部门',dataIndex:'department',width:'15%'},
        {title:'职位',dataIndex:'position',width:'15%'},
        {title:'邮箱',dataIndex:'email',width:'20%'},
        {title: '操作', width: '10%', renderer: function(value, obj) {
      	  //return '编辑';
      	  //var authBtn = Search.createLink({
          //    id : 'authSetting' + obj.id,
          //    title : '用户权限设置',
          //    text : '权限设置',
          //    href : '<%=contextPath %>/usermgr/userAuthSetting.do?userId=' + obj.id
          //  });
      	  var authBtn = '<span class="grid-command"><a href="#" onclick="javascript: authSetting(\''+ obj.id + '\'); return false;">'
				+'权限设置</a></span>';
      	  var editBtn = '<span class="grid-command btn-edit">编辑</span>';
      	  if (!isAdmin)
      		  return editBtn;
      	  
      	  if (obj.name == "admin")
      		  return editBtn;
      	  return editBtn + authBtn;
        }}
        /* {title:'操作',dataIndex:'',width:200,renderer : function(value,obj){
          var editStr =  Search.createLink({ //链接使用 此方式
              id : 'edit' + obj.id,
              title : '编辑学生信息',
              text : '打开编辑',
              href : 'form/example.html'
            }),
            editStr1 = '<span class="grid-command btn-edit" title="编辑学生信息">弹出编辑</span>',
            delStr = '<span class="grid-command btn-del" title="删除学生信息">删除</span>';//页面操作不需要使用Search.createLink
          return editStr +  editStr1 + delStr;
        }} */
      ];
      var store = Search.createStore('<%=contextPath %>/usermgr/getUsers.do', {
    	  proxy: {
      		method: "post",
      		dataType : 'json',
      		save : { //也可以是一个字符串，那么增删改，都会往那么路径提交数据，同时附加参数saveType
				addUrl : '<%=contextPath %>/usermgr/editUser.do?action=add',
				updateUrl : '<%=contextPath %>/usermgr/editUser.do?action=update',
				removeUrl : '<%=contextPath %>/usermgr/editUser.do?action=remove'
         	}
    	  }
      });
      
      var gridCfg = Search.createGridCfg(columns, {
        tbar : {
          items : [
            {text : '<i class="icon-plus"></i>新建',btnCls : 'button button-small',handler: addFunction},
            /* {text : '<i class="icon-edit"></i>编辑',btnCls : 'button button-small',handler:function(){alert('编辑');}}, */
            {text : '<i class="icon-remove"></i>删除',btnCls : 'button button-small',handler : delFunction}
          ]
        },
        plugins : [BUI.Grid.Plugins.CheckSelection,editing] // 插件形式引入多选表格
      });

    var search = new Search({
        store : store,
        gridCfg : gridCfg
      });
    var grid = search.get('grid');
 	// 当使用editing查看明细时必须调用该方法
   // initEditing(editing);
    //initSearchAndStore(search, store);
    initComponent(search, editing, store);
    
    // 新增操作
    function addFunction(){
        var newData = {isNew : true}; //标志是新增加的记录
        editing.add(newData); //添加记录后，直接编辑
    }
    
    // 删除操作
    function delFunction(){
      var selections = grid.getSelection();
      delItems(selections);
    }

    function delItems(items){
      var ids = [];
      BUI.each(items,function(item){
    	  if (item.name != "admin")
        	ids.push(item.id);
      });

      if(ids.length){
        BUI.Message.Confirm('确认要删除选中的记录么？',function(){
        	$.post('<%=contextPath %>/usermgr/editUser.do?action=remove', {ids: ids}, function(ret) {
        		if(ret.success){ //删除成功
                	search.load();
                	BUI.Message.Alert('删除成功！');
                } else { //删除失败
                    BUI.Message.Alert('删除失败！');
                }
        	}, 'json');
        },'question');
      } else {
      	BUI.Message.Alert("请选择一个用户执行该操作，注意：admin用户不能被删除！");
      }
    } 
    
    authSetting = function(userId) {
		  var treeStore = createUserMenuStore(userId);
		  var tree = createUserMenuTree(userId, treeStore);

		  var dialog = new BUI.Overlay.Dialog({
	        title: '编辑人员将权限',
	        width: 340,
	        height: 505,
	        contentId: 'authSetting',
	        success:function () {
	          var menus = getCheckedMenus(tree);
	          $.post('<%=contextPath %>/usermgr/saveUserMenu.do?', {userId: userId, menus: menus},
	        		  function(result) {
	        	  if (result.success) {
	        		  BUI.Message.Alert('权限设置成功！', function(){
	        			  dialog.close();
			   	        }, 'success');
	        	  } else {
	        		  BUI.Message.Alert("权限设置失败，请稍后重试！", 'error');
	        	  }
	          }, 'json');
	          
	          $("#authSetting").empty();
	        }
	      });
	    dialog.show();
	};

		 function createUserMenuStore(userId) {
			var store = new BUI.Data.TreeStore({
				autoLoad : true,
				url: '<%=contextPath %>/usermgr/getUserMenu.do?userId=' + userId
			});
			  
			return store;
		 }

		 function createUserMenuTree(userId, store) {
			//由于这个树，不显示根节点，所以可以不指定根节点
			var tree = new BUI.Tree.TreeList({
			  	render : '#authSetting',
			  	store : store,
			  	height: 440,
			  	checkType: 'all', //checkType:勾选模式，提供了4中，all,onlyLeaf,none,custom
			  	showLine : true //显示连接线
			});
			tree.render();
			return tree;
		 }
		 
		 function getCheckedMenus(treeObj) {
			 var menus = "";
			 var nodes = treeObj.getCheckedNodes();
			 if (!nodes || nodes.length == 0)
				 return menus;
			 
			 var idx = 0;
			 for (; idx < nodes.length - 1; )
			 for (var idx in nodes) {
				 menus += (nodes[idx].id + ",");
			 }
			 menus += nodes[idx].id;
			 
			 return menus;
		 }
    
    
    //监听事件，删除一条记录
/*     grid.on('cellclick',function(ev){
      var sender = $(ev.domTarget); //点击的Dom
      if(sender.hasClass('btn-del')){
        var record = ev.record;
        delItems([record]);
      }
    }); */
    
    //监听事件，删除一条记录
    grid.on('cellclick', function(ev) {
    	var sender = $(ev.domTarget);
       var editor = editing.get('editor');
       var contain = false;
		if(sender.hasClass('btn-edit') && editor){
			contain = true;
			editing.edit(ev.record);
		}
       if (sender.hasClass('btn-view') && editor) {
       	contain = true;
     		var record = ev.record;
     		var view = {"view": true};
     		record.trigger_action = "view";
     		editing.showEditor(record);
     		setEditingEnable(editing, false);
     	}
       if (contain && grid.get('multipleSelect')){
		    return false;
		}
   });
    
});

</script>

		
</body>
</html>